import {_decorator, Component, instantiate, Node, ScrollView, UITransform, Vec3, Label, Widget} from 'cc';

const {ccclass, property} = _decorator;

//滚动视图
@ccclass('ScrollViewScript')
export class ScrollViewScript extends Component {
    @property(ScrollView)
    scrollview !: ScrollView;
    @property(Node)
    itemButton!: Node;
    @property(Node)
    buttonGroup!: Node;

    //item 数量
    itemCount: number = 0;

    //item数组
    itemArr: Node[] = []

    onLoad() {
        this.init()
    }

    start() {
        let content = this.scrollview.content

        for (let i = 0; i < this.itemCount; i++) {
            let element = this.itemArr[i];
            for (let child of element.children) {
                child.getComponent(Label)!.string = 'item按钮' + i
            }
            element.getComponent(Widget).top = 20 + (60 * i)
            content.addChild(element)
        }

    }

    update(deltaTime: number) {

    }

    init() {
        this.itemCount = 3
        let content = this.scrollview.content
        this.setScrollViewHeight()
        for (let i = 0; i < this.itemCount; i++) {
            let node = instantiate(this.itemButton);
            this.itemArr.push(node)
            content.addChild(node)
        }
        console.log("实例个数：" + this.itemArr.length)
    }

    setScrollViewHeight() {
        this.scrollview.content.getComponent(UITransform)!.height = this.itemCount * (this.itemButton.getComponent(UITransform).height + 20)
    }

    add() {
        this.itemCount++
        let content = this.scrollview.content
        this.setScrollViewHeight()
        let node = instantiate(this.itemButton);
        for (let child of node.children) {
            child.getComponent(Label)!.string = 'item按钮' + (this.itemCount - 1)
        }
        node.getComponent(Widget).top = 20 + (60 * this.itemCount) - 60
        content.addChild(node)
        this.itemArr.push(node)
    }

    min() {
        this.itemCount--
        let content = this.scrollview.content
        let children = content.children;
        content.removeChild(children[children.length - 1])
        this.itemArr.pop()
        this.setScrollViewHeight()
    }
}


